'use strict';

const crypto = require('crypto');

const keyStr = '82c22b07c5654dcf';
const ivRender = 'qwerty1234rfidjs';
const aesObj = {
    '16': 'aes-128-gcm',
    '24': 'aes-192-gcm',
    '32': 'aes-256-gcm',
}


function encrypt(word, keys) {
    if (!word) return '';
    if (typeof word != 'string') word = JSON.stringify(word);
    const keyTxt = keys || keyStr;
    const algorithm = aesObj[keyTxt.length];
    const md5 = crypto.createHash('md5');
    const result = md5.update(keyTxt).digest();
    const cipher = crypto.createCipheriv(algorithm, result, ivRender);
    const encrypted = cipher.update(word, 'utf8');
    const finalstr = cipher.final();
    const tag = cipher.getAuthTag();
    const res = Buffer.concat([encrypted, finalstr, tag]);
    return res.toString('base64');

}

function decrypt(word, keys) {
    if (!word) return '';
    const keyTxt = keys || keyStr;
    const algorithm = aesObj[keyTxt.length];
    const md5 = crypto.createHash('md5');
    const result = md5.update(keyTxt).digest();
    const decipher = crypto.createDecipheriv(algorithm, result, ivRender);
    const b = Buffer.from(word, 'base64');
    decipher.setAuthTag(b.subarray(b.length - 16));
    const str = decipher.update(Buffer.from(b.subarray(0, b.length - 16), 'hex'));
    const fin = decipher.final();
    const decryptedStr = new TextDecoder('utf8').decode(Buffer.concat([str, fin]))

    try {
        return JSON.parse(decryptedStr);
    } catch (e) {
        return decryptedStr
    }

}

// code加密
function enCodeUrl (str) {
    let baseTxt = window.encodeURIComponent(str);
    return baseTxt.replace(/%/ig, '_');
}

